package com.zhucai.credit.monitor.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.jms.Queue;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zhucai.credit.monitor.bean.SMSNotificationParam;
import com.zhucai.credit.monitor.bean.SendMsgResult;
import com.zhucai.credit.monitor.service.INotificationService;

@Service("SMS")
public class SMSNotificationServiceImpl implements INotificationService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private Queue queue;
	
	
	@Value("${notification.sms.sendto}")
	private String sendTo;
	
	@Value("${notification.sms.expire}")
	private Integer expire;
	
	@Value("${notification.sms.issend}")
	private String sendtatus;
	
	
	@Autowired
	private RedisTemplate<String,String> snsRecorder;
	
	@PostConstruct
	public void notificationStart() {
		notification("短信监控开始");
	}
	
	@Override
	public SendMsgResult notification(String message) {
		if(!"true".equalsIgnoreCase(sendtatus)){
			return null;
		}
		String buildKey = buildKey(message);
		String sns = snsRecorder.opsForValue().get(buildKey);
		if(StringUtils.isBlank(sns)) {
			//未发、做记录
			snsRecorder.opsForValue().set(buildKey,message);
			snsRecorder.expire(buildKey, expire, TimeUnit.MINUTES);  
		} else {
			//已发
			return new SendMsgResult(0, "send");
		}

		try {
			SMSNotificationParam smsNotificationParam = new SMSNotificationParam(sendTo,getHostName()+":"+message,2);

			String jsonString = JSON.toJSONString(smsNotificationParam);
			jmsTemplate.convertAndSend(queue, jsonString);
			logger.info("信息发送成功...sendTo={},message={},queueName={}",sendTo,message,queue.getQueueName());
			return new SendMsgResult(1, "success");
		} catch (Exception e) {
			return new SendMsgResult(0, "fail");
		}
	}
	
	private String getHostName() {
        try {
			InetAddress addr = InetAddress.getLocalHost();  
			String hostName=addr.getHostName().toString();
			return hostName;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        return "";
	}
	
	private String buildKey(String message) {
		return "credit.monitor.sns.recorder."+message.hashCode();
	}
}
